import Vue from "vue";
import Main from "./main.vue";
import { PopupManager } from "@/utils/popup";
import { isVNode } from "@/utils/vdom";
let MessageConstructor = Vue.extend(Main); // 返回这个组件的构造函数

let instance;
let instances = [];
let seed = 1;

const Message = function(options) {
  if (Vue.prototype.$isServer) return; // 服务端渲染 就退出
  options = options || {};
  // 传进来的是字符串的话
  if (typeof options === "string") {
    options = {
      message: options
    };
  }
  let userOnClose = options.onClose;
  let id = "message_" + seed++;

  options.onClose = function() {
    console.log("chufa zijide ");
    Message.close(id, userOnClose); // 加上静态方法
  };
  // 传入data
  instance = new MessageConstructor({
    data: options
  });
  instance.id = id;
  // instance.message是否是一个 vnode  h('p', null, [
  //     h('span', null, '内容可以是 '),
  //     h('i', { style: 'color: teal' }, 'VNode')
  //   ])
  if (isVNode(instance.message)) {
    instance.$slots.default = [instance.message];
    instance.message = null;
  }
  // 挂载
  instance.$mount();
  console.log(instance.id);
  document.body.appendChild(instance.$el);
  // 向下偏移的距离
  let verticalOffset = options.offset || 20;
  instances.forEach(item => {
    verticalOffset += item.$el.offsetHeight + 16;
  });
  instance.verticalOffset = verticalOffset;
  instance.visible = true;
  instance.$el.style.zIndex = PopupManager.nextZIndex();
  instances.push(instance);
  return instance;
};

// 为这个函数加上 这些个属性
["success", "warning", "info", "error"].forEach(type => {
  Message[type] = options => {
    if (typeof options === "string") {
      options = {
        message: options
      };
    }
    options.type = type;
    return Message(options);
  };
});

// 调用这个关闭方法
Message.close = function(id, userOnClose) {
  let len = instances.length;
  let index = -1;
  let removedHeight;
  for (let i = 0; i < len; i++) {
    if (id === instances[i].id) {
      removedHeight = instances[i].$el.offsetHeight;
      index = i;
      if (typeof userOnClose === "function") {
        userOnClose(instances[i]);
      }
      instances.splice(i, 1);
      break;
    }
  }
  // 调整其余的高度
  if (len <= 1 || index === -1 || index > instances.length - 1) return;
  for (let i = index; i < len - 1; i++) {
    let dom = instances[i].$el;
    dom.style["top"] =
      parseInt(dom.style["top"], 10) - removedHeight - 16 + "px";
  }
};

Message.closeAll = function() {
  for (let i = instances.length - 1; i >= 0; i--) {
    instances[i].close();
  }
};

export default Message;
